package com.example.design.beautiful.unit_test.performance_counter.v2.reporter;

import com.example.design.beautiful.unit_test.performance_counter.aggregator.RequestStat;
import com.example.design.beautiful.unit_test.performance_counter.collector.RequestInfo;
import com.example.design.beautiful.unit_test.performance_counter.strorage.MetricsStorage;
import com.example.design.beautiful.unit_test.performance_counter.v2.Aggregator;
import com.example.design.beautiful.unit_test.performance_counter.v2.view.StatViewer;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ConsoleReporter {
  private MetricsStorage metricsStorage;
  private ScheduledExecutorService executor;
  private Aggregator aggregator;
  private StatViewer statViewer;

  public ConsoleReporter(MetricsStorage metricsStorage, Aggregator aggregator, StatViewer statViewer) {
    this.metricsStorage = metricsStorage;
    this.executor = Executors.newSingleThreadScheduledExecutor();
    this.aggregator = aggregator;
    this.statViewer = statViewer;
  }
  
  // 第4个代码逻辑：定时触发第1、2、3代码逻辑的执行；
  public void startRepeatedReport(long periodInSeconds, long durationInSeconds) {
    executor.scheduleAtFixedRate(() -> {
      // 第1个代码逻辑：根据给定的时间区间，从数据库中拉取数据；
      long durationInMillis = durationInSeconds * 1000;
      long endTimeInMillis = System.currentTimeMillis();
      long startTimeInMillis = endTimeInMillis - durationInMillis;
      Map<String, List<RequestInfo>> requestInfos =
              metricsStorage.getRequestInfos(startTimeInMillis, endTimeInMillis);

      // todo 这块代码可以放到aggregator中
//      Map<String, RequestStat> stats = new HashMap<>();
//      for (Map.Entry<String, List<RequestInfo>> entry : requestInfos.entrySet()) {
//        String apiName = entry.getKey();
//        List<RequestInfo> requestInfosPerApi = entry.getValue();
//        // 第2个代码逻辑：根据原始数据，计算得到统计数据；
//        RequestStat requestStat = Aggregator.aggregate(requestInfosPerApi, durationInMillis);
//        stats.put(apiName, requestStat);
//      }
      Map<String, RequestStat> aggregate = aggregator.aggregate(requestInfos,durationInMillis);


      // todo 将这部分逻辑剥离出来，设计成类
      // 第3个代码逻辑：将统计数据显示到终端（命令行或邮件）；
//      System.out.println("Time Span: [" + startTimeInMillis + ", " + endTimeInMillis + "]");
//      Gson gson = new Gson();
//      System.out.println(gson.toJson(stats));
      statViewer.output(aggregate, startTimeInMillis, durationInMillis);

    }, 0, periodInSeconds, TimeUnit.SECONDS);
  }
}

